﻿using Sidvall.Serialization;

namespace Sidvall.AuthorizationManager.Data
{
	public static class ConnectionTypeManager
	{
		#region Public Members

		#region GetConnectionDescription

		public static string GetConnectionDescription(ConnectionType type, string address, string connectionString)
		{
			string[] items, parts;
			string result, server, database;

			switch (type)
			{
				case ConnectionType.NetworkSqlServer:
					if (string.IsNullOrWhiteSpace(connectionString))
						return connectionString;
					server = "";
					database = "";
					items = connectionString.Split(";", System.StringSplitOptions.RemoveEmptyEntries);
					foreach (var item in items)
					{
						parts = item.Split("=");
						if (parts[0].StartsWith("data source", System.StringComparison.OrdinalIgnoreCase))
							server = parts[1];
						else if (parts[0].StartsWith("server", System.StringComparison.OrdinalIgnoreCase))
							server = parts[1];
						else if (parts[0].StartsWith("initial catalog", System.StringComparison.OrdinalIgnoreCase))
							database = parts[1];
						else if (parts[0].StartsWith("database", System.StringComparison.OrdinalIgnoreCase))
							database = parts[1];
					}
					result = server;
					if (!string.IsNullOrWhiteSpace(database))
					{
						if (!string.IsNullOrWhiteSpace(server))
							result += "/";
						result += database;
					}
					return result;
				case ConnectionType.RemoteAccess:
					return address;
				default:
					return "";
			}
		}

		#endregion
		#region GetConnectionString

		public static string GetConnectionString(string connectionString)
		{
			System.Text.StringBuilder sb;

			sb = new System.Text.StringBuilder();
			sb.Append("metadata=res://Sidvall.AuthorizationManager.Data.Entity/Model.Model.csdl|res://Sidvall.AuthorizationManager.Data.Entity/Model.Model.ssdl|res://Sidvall.AuthorizationManager.Data.Entity/Model.Model.msl;provider=System.Data.SqlClient;provider connection string=\"");
			sb.Append(connectionString.ToString(string.Empty).TrimEnd(';') + ";");
			sb.Append("MultipleActiveResultSets=True;App=EntityFramework;");
			sb.Append("\"");
			return sb.ToString();

		}

		#endregion
		#region IsRemote

		public static bool IsRemote(ConnectionType type)
		{
			switch (type)
			{
				case ConnectionType.RemoteAccess:
					return true;
				default:
					return false;
			}
		}

		#endregion
		#region IsSqlServer

		public static bool IsSqlServer(ConnectionType type)
		{
			switch (type)
			{
				case ConnectionType.NetworkSqlServer:
					return true;
				default:
					return false;
			}
		}

		#endregion

		#endregion
	}
}
